const router = require("koa-router")();


const UserCode = require('../../model/UserCode')

const { checkMobile  } = require('../../utils/validate')

const  { sendLocalMessage } = require('../websocket') 

// 生成并且发生验证码
router.get('/codes/:mobile', async (ctx, next) => {
  const { mobile } = ctx.params
  if (!mobile || !(checkMobile(mobile))) {
      return  { success: false, message: "手机号不存在或者格式不正确", status: 404 }
  }
   const codeOne = await UserCode.findOne({ mobile }).lean()
   if (codeOne) {
       const interval = parseInt((Date.now() - codeOne.timer) / 1000 - 60) 
    if (interval < 0 ) {
        return {  success: false, message: `发送验证码过于频繁,请${Math.abs(interval)}秒之后再试`, status: 429 }
    }else{
        const code = createCode() // 生成随机验证码
        await UserCode.findOneAndUpdate(codeOne, { code, timer: Date.now() })
        sendLocalMessage('message', `[极客园]验证码<a onclick="copyValue(this)" href="javascript:void(0)">${code}</a>,用于手机号<a  onclick="copyValue(this)" href="javascript:void(0)">${mobile}</a>登录, 5分钟内有效。验证码提供给他人可能导致账号被盗,请勿泄露，谨防被骗`) // 发送验证码到本地服务
    }
   }else {
    const code = createCode() // 生成随机验证码
    await UserCode.create({mobile, code, timer: Date.now() })
    sendLocalMessage('message', `[极客园]验证码<a onclick="copyValue(this)" href="javascript:void(0)">${code}</a>,用于手机号<a  onclick="copyValue(this)" href="javascript:void(0)">${mobile}</a>登录, 5分钟内有效。验证码提供给他人可能导致账号被盗,请勿泄露，谨防被骗`) // 发送验证码到本地服务
   }
   ctx.status = 200
})
const createCode = () => {
    let code = ""
    for(var i = 1;i <= 6;i++){
        const num = Math.floor(Math.random()*10);
        code += num;
    }
    return code
}
module.exports = router.routes();
